<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <title>按 PX 生成方格（根据分辨率计算）</title>
    <style>
        body{
            font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial;
            margin: 12px;
            line-height: 1.4;
        }
        .controls{
            display:flex;
            gap:12px;
            align-items:center;
            margin-bottom:12px;
            flex-wrap:wrap;
        }
        input[type="number"]{ width:88px; padding:6px; }
        button{ padding:6px 10px; }
        .info { font-size:13px; color:#444; }

        /* 网格容器 —— 使用 CSS Grid 布局 */
        .grid {
            width:100%;
            height: calc(100vh - 150px); /* 留一点顶部控件高度 */
            border: 1px solid #ddd;
            box-sizing: border-box;
            overflow: auto;
            background: repeating-linear-gradient(45deg, rgba(0,0,0,0.01) 0 1px, transparent 1px 50px);
        }

        .grid-inner{
            display: grid;
            justify-items: stretch;
            align-items: stretch;
            width:100%;
            height:100%;
        }

        .cell{
            box-sizing: border-box;
            border: 1px solid rgba(0,0,0,0.06);
            display:flex;
            align-items:center;
            justify-content:center;
            font-size:11px;
            color: rgba(0,0,0,0.45);
            user-select: none;
            background: linear-gradient(180deg, rgba(255,255,255,0.02), rgba(0,0,0,0.01));
        }
        .footer { margin-top:10px; font-size:13px; color:#666; }
    </style>
</head>
<body>
<h3>根据分辨率按 px 生成方格</h3>

<div class="controls">
    <label>方格大小 (px): <input id="cellSize" type="number" min="4" value="50"></label>
    <label>是否显示坐标: <input id="showIdx" type="checkbox"></label>
    <button id="generate">生成方格</button>
    <button id="fitScreen">适配当前屏幕</button>
    <div class="info" id="screenInfo"></div>
</div>

<div class="grid" id="grid">
    <div class="grid-inner" id="gridInner"></div>
</div>

<div class="footer">
    说明：使用 <code>window.innerWidth</code> / <code>window.innerHeight</code> 作为 CSS 像素的可视窗口尺寸；如果你想基于设备物理像素，请乘以 <code>window.devicePixelRatio</code>。
    窗口尺寸变化会自动更新（你也可以点击“生成方格”）。
</div>

<script>
    const cellSizeInput = document.getElementById('cellSize');
    const showIdxCheckbox = document.getElementById('showIdx');
    const generateBtn = document.getElementById('generate');
    const fitBtn = document.getElementById('fitScreen');
    const gridInner = document.getElementById('gridInner');
    const screenInfo = document.getElementById('screenInfo');

    function getViewportInfo(){
        const cssW = window.innerWidth;
        const cssH = window.innerHeight;
        const screenW = window.screen.width;
        const screenH = window.screen.height;
        const dpr = window.devicePixelRatio || 1;
        return { cssW, cssH, screenW, screenH, dpr };
    }

    function renderGrid(){
        const size = Math.max(4, parseInt(cellSizeInput.value) || 50);
        const showIdx = showIdxCheckbox.checked;
        const { cssW, cssH, screenW, screenH, dpr } = getViewportInfo();

        // 计算列数和行数（使用可见窗口大小 innerWidth/innerHeight）
        const cols = Math.max(1, Math.floor(cssW / size));
        const rows = Math.max(1, Math.ceil((cssH - 150) / size)); // 减掉顶部控件高度的近似值

        screenInfo.textContent = `窗口 (CSS 像素): ${cssW}×${cssH}  · 屏幕 (device pixels): ${Math.round(screenW*dpr)}×${Math.round(screenH*dpr)}  · devicePixelRatio: ${dpr}  · 计算: ${cols} 列 × ${rows} 行`;

        // 设置 grid-template
        gridInner.style.gridTemplateColumns = `repeat(${cols}, ${size}px)`;
        gridInner.style.gridAutoRows = `${size}px`;

        // 清空旧方格
        gridInner.innerHTML = '';

        // 创建方格（注意大量方格可能会影响性能）
        const total = cols * rows;
        for(let i=0;i<total;i++){
            const cell = document.createElement('div');
            cell.className = 'cell';
            if(showIdx) {
                const r = Math.floor(i / cols) + 1;
                const c = (i % cols) + 1;
                cell.textContent = `${r},${c}`; // 展示行列
            }
            gridInner.appendChild(cell);
        }
    }

    // 自动在窗口大小调整时刷新（节流）
    let resizeTimer = null;
    window.addEventListener('resize', ()=>{
        if(resizeTimer) clearTimeout(resizeTimer);
        resizeTimer = setTimeout(()=>{ renderGrid(); }, 120);
    });

    generateBtn.addEventListener('click', renderGrid);
    fitBtn.addEventListener('click', ()=>{
        // 将方格大小设为能整除宽度的值（可选策略）
        const { cssW } = getViewportInfo();
        const desiredCols = Math.max(6, Math.floor(cssW / 50)); // 期望列数（示例策略）
        const newSize = Math.floor(cssW / desiredCols);
        cellSizeInput.value = newSize;
        renderGrid();
    });

    // 首次渲染
    renderGrid();
</script>
</body>
</html>
